<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>在线聊天室</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container" style="margin-top: 20px;">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h4 class="panel-title">在线聊天室（基于长轮训）</h4>
        </div>

        <div class="panel-body">
            <div class="form-group">
                <div class="form-inline">
                    <input id="user-name" type="text" class="form-control" placeholder="请输入用户名"/>
                    <button id="into-chat-room" type="button" class="btn btn-primary">进入聊天室</button>
                    <button id="leave-chat-room" type="button" class="btn btn-danger" style="display:none">离开聊天室
                    </button>
                </div>
            </div>

            <div class="form-group">
                <div id="chat-screen" style="height:400px;border:1px solid green;overflow:auto;padding: 5px;"></div>
            </div>

            <div class="form-group">
                <input id="message-text" type="text" class="form-control" placeholder="请输入聊天内容">
            </div>

            <div class="form-group">
                <input id="send-message" type="button" class="btn btn-success" value="发送消息(Enter)">
                <input id="clean-screen" type="button" class="btn btn-info" value="清屏">
            </div>
        </div>
    </div>

</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"
        integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
        crossorigin="anonymous"></script>
<script>
    var userName;
    var userId;
    var needPull;

    var $userNameInput = $('#user-name');
    var $btnIntoChatRoom = $('#into-chat-room');
    var $btnLeaveChatRoom = $('#leave-chat-room');
    var $chatScreen = $('#chat-screen');
    var $messageText = $('#message-text');
    var $sendMessage = $('#send-message');
    var $cleanScreen = $('#clean-screen');

    $btnIntoChatRoom.click(function () {
        userName = $userNameInput.val();
        if (!userName) {
            alert('请先输入用户名');
            return;
        }

        $.ajax({
            url: "/chat/intoChatRoom",
            data: {
                "userName": userName
            },
            success: function (data) {
                userId = data.data;
                appendScreenContent(userName + "进入聊天室");
                showLeaveBtn();

                needPull = true;
                pullData();
            }
        });
    });

    function pullData() {
        $.ajax({
            url: "/chat/pullData",
            data: {
                "userId": userId
            },
            success: function (data) {
                var list = data.data;
                if (list && list.length) {
                    $.each(list, function (i, n) {
                        appendScreenContent(n.userName + ":" + n.content);
                    });
                }
                if (needPull) {
                    pullData();
                }
            }

        });
    }

    $btnLeaveChatRoom.click(function () {
        needPull = false;
        showIntoBtn();
    });

    $messageText.keyup(function (event) {
        if (event.keyCode === 13) {
            var message = $messageText.val();
            if (message) {
                sendMessage(message);
                $messageText.val("");
            }
        }
    });

    $sendMessage.click(function () {
        var message = $messageText.val();
        if (message) {
            sendMessage(message);
            $messageText.val("");
        } else {
            alert("请输入聊天内容！");
        }
    });

    $cleanScreen.click(function () {
        $chatScreen.html("");
    });

    function showIntoBtn() {
        $userNameInput.removeAttr("readonly");
        $btnIntoChatRoom.show();
        $btnLeaveChatRoom.hide();
    }

    function showLeaveBtn() {
        $userNameInput.attr("readonly", "readonly");
        $btnIntoChatRoom.hide();
        $btnLeaveChatRoom.show();
    }

    function appendScreenContent(message) {
        $chatScreen.append($("<p>").text(message));
    }

    function sendMessage(message) {
        if (userId) {
            $.ajax({
                url: "/chat/sendMessage",
                data: {
                    "userId": userId,
                    "content": message
                },
                success: function (data) {
                }
            });
        } else {
            alert("请先进入聊天室！");
        }
    }
</script>
</html>